package com.huyanqi.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.huyanqi.core.util.FileUploadUtils;
import com.huyanqi.entity.Share;
import com.huyanqi.entity.User;
import com.huyanqi.service.ShareService;
import com.huyanqi.service.UserService;

@Controller
public class ShareController {

	private ShareService shareService;
	private UserService userService;
	public UserService getUserService() {
		return userService;
	}
	public ShareService getShareService() {
		return shareService;
	}
	@Resource(name="ShareService")
	public void setShareService(ShareService shareService) {
		this.shareService = shareService;
	}
	@Resource(name="UserService")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping("/shareUpload.do")
	@ResponseBody
	public String shareUpload(String content,Long uid,MultipartHttpServletRequest request){
		try {
			content = URLDecoder.decode(content, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		MultipartFile file = request.getFile("file1");
		if (!file.isEmpty()){
            try {
            	String fileName = file.getOriginalFilename();
            	String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	fileName = UUID.randomUUID().toString()+suffix;
            	FileUploadUtils.copyFile(file.getInputStream(), fileName,request.getSession().getServletContext().getRealPath("share"));
            	Share s = new Share();
            	s.setUsImg(fileName);
            	s.setUsContent(content);
            	s.setUsUid(uid);
            	shareService.save(s);
            	User u = userService.findById(uid);
            	u.setUShareNum(u.getUShareNum()+1);
            	userService.update(u);
            	return "ok";
			} catch (Exception e) {
				e.printStackTrace();
			}
       }
		return null;
	}
	
}
